# from django.db.models import Max

from api import netbox_api
# from netbox import models
# from django.forms.models import model_to_dict

# 日志输出常量定义
from loguru import logger
logger.add("/var/log/Task/netbox/Tasks.log", rotation="00:00", backtrace=True, diagnose=True, level="DEBUG")


def update_db(dict_data, netbox_url, netbox_token, verify):
    """
    该功能用于同步数据库更新并根据更新情况判断返回信息的数据
    在更新 info 表时同时添加一条 history 表数据用于存储更新记录
    :param dict_data: 更新发送过来的所有的字段及数据
    :param netbox_url: netbox_url
    :param netbox_token: netbox_token
    :param verify: verify
    :return: 提示消息数据
    """
    if dict_data["data"].get("termination_z", None):
        provider_network = dict_data["data"]["termination_z"]["provider_network"]["name"]
    else:
        provider_network = None
    if dict_data["data"].get("termination_a", None):
        site_name = dict_data["data"]["termination_a"]["site"]["name"]
        site_slug = dict_data["data"]["termination_a"]["site"]["slug"]
    else:
        site_name = None
        site_slug = None
    new_data = {
        "id": dict_data["data"]["id"],
        "cid": dict_data["data"]["cid"],
        "linecode": dict_data["data"]["custom_fields"]["LineCode"],
        "provider_name": dict_data["data"]["provider"]["name"],
        "line_type": dict_data["data"]["type"]["name"],
        "status": dict_data["data"]["status"]["label"],
        "tenant": dict_data["data"]["tenant"]["name"],
        "site_name": site_name,
        "site_slug": site_slug,
        "provider_network": provider_network,
        "commit_rate": dict_data["data"]["commit_rate"],
        "available_ip": dict_data["data"]["custom_fields"]["AvailableIP"],
        "ipaddress": dict_data["data"]["custom_fields"]["IPAddress"],
        "mask": dict_data["data"]["custom_fields"]["Mask"],
        "natip_pool": dict_data["data"]["custom_fields"]["NatIPPool"],
        "gateway": dict_data["data"]["custom_fields"]["Gateway"],
        "comments": dict_data["data"]["comments"],
    }

    # 执行数据库更新
    update_info_date = update_info(new_data, netbox_url, netbox_token, verify=verify)

    # 获取跟新历史中 更新字段
    max_id = models.history.objects.filter(line_id=new_data["id"], option_type="update").aggregate(Max('id'))[
        "id__max"]
    history_obj = models.history.objects.filter(line_id=new_data["id"], option_type="update", id=max_id).first()
    if history_obj:
        old_kv = eval(history_obj.old_kv)
        new_kv = eval(history_obj.new_kv)
    else:
        old_kv = {}
        new_kv = {}
    update_str = ""
    if new_kv:
        for k, v in new_kv.items():
            if old_kv[k]:
                update_str += f"{k}<({old_kv[k]})-->({new_kv[k]})>\n"
            else:
                update_str += f"{k}<(None)-->({new_kv[k]})>\n"

    # 调用企微机器人对更新结果进行消息通知。
    termination_name = dict_data["data"]["termination_a"]["site"]["name"]
    line_id = dict_data["data"]["cid"]
    if update_info_date["option"] == "update":
        if not update_str:
            return False
        content = f"#### Netbox线路信息刷新\n" \
                  f">**本次更新内容:**\n" \
                  f"{termination_name}站点，{line_id}线路 \n" \
                  f">**更新字段:**\n{update_str} \n" \
                  f"[最新园区网外线信息表](http://grafana-it.int.xiaohongshu.com/d/yZ8fyv6nk/it-network-office-line-info-table" \
                  f"?orgId=1)  [[权限申请]](https://wiki.xiaohongshu.com/pages/viewpage.action?pageId=205529607)"
    elif update_info_date["option"] == "create":
        content = ""

    else:
        content = "#### 更新数据库操作失败"
    return content


def update_info(data, netbox_url, netbox_token, verify=None):
    # 获取现在netbox中线路数据的数量
    netbox_circuits = netbox_api.netbox_get_circuits(netbox_url, netbox_token, verify=verify)
    count = netbox_circuits["count"]

    # 查询数据库中线路数据数量
    db_circuits = models.info.objects.all()
    db_count = len(db_circuits)

    # 如果数据库中数据量与netbox中数据量不一致，则清空表数据重新创建
    if db_count != count:
        # 获取netbox中的数据
        results = netbox_circuits.get("results")

        # 将数据库中数据清空
        auths = models.info.objects.all()
        auths.delete()  # 删除

        # 创建数据
        for i in results:
            provider_network = i.get("termination_z", None)
            if provider_network:
                provider_network_name = provider_network["provider_network"]["name"]
            else:
                provider_network_name = None
            site = i.get("termination_a", None)
            if site:
                site_name = site["site"]["name"]
                site_slug = site["site"]["slug"]
            else:
                site_name = None
                site_slug = None
            models.info.objects.create(id=i["id"], cid=i["cid"], linecode=i["custom_fields"]["LineCode"],
                                       provider_name=i["provider"]["name"], line_type=i["type"]["name"],
                                       status=i["status"]["label"], tenant=i["tenant"]["name"],
                                       site_name=site_name,
                                       site_slug=site_slug,
                                       provider_network=provider_network_name,
                                       commit_rate=i["commit_rate"],
                                       available_ip=i["custom_fields"]["AvailableIP"],
                                       ipaddress=i["custom_fields"]["IPAddress"],
                                       mask=i["custom_fields"]["Mask"], natip_pool=i["custom_fields"]["NatIPPool"],
                                       gateway=i["custom_fields"]["Gateway"],
                                       comments=i["comments"])
        resp_msg = {"msg": "数据库与netbox数据量不一致，执行初始化操作", "option": "create"}
        # logger.info(resp_msg)

    else:
        info_obj = models.info.objects.filter(id=data["id"]).first()
        old_dict = {}
        new_dict = {}
        if info_obj:
            info_dict = model_to_dict(info_obj)
            for k, v in info_dict.items():
                # new_value = getattr(self, k)
                if v != data[k]:
                    old_dict[k] = v
                    new_dict[k] = data[k]
        models.history.objects.create(
            line_id=data["id"],
            old_kv=str(old_dict),
            new_kv=str(new_dict),
            option_type="update",
        )
        models.info.objects.filter(id=data["id"]).update(id=data["id"], cid=data["cid"], linecode=data["linecode"],
                                                         provider_name=data["provider_name"],
                                                         line_type=data["line_type"],
                                                         status=data["status"], tenant=data["tenant"],
                                                         site_name=data["site_name"],
                                                         site_slug=data["site_slug"],
                                                         provider_network=data["provider_network"],
                                                         commit_rate=data["commit_rate"],
                                                         available_ip=data["available_ip"],
                                                         ipaddress=data["ipaddress"], mask=data["mask"],
                                                         natip_pool=data["natip_pool"],
                                                         gateway=data["gateway"],
                                                         comments=data["comments"])
        resp_msg = {"msg": f"更新线路{data['id']}", "option": "update"}
        # logger.info(resp_msg)
    return resp_msg
